import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PERMISSION_KEY } from './permission.decorator';
import { AuthService } from 'src/auth/auth.service';

@Injectable()
export class AuthPermissionGuard implements CanActivate {
	constructor(private reflector: Reflector, private readonly authService: AuthService) {}

	async canActivate(context: ExecutionContext): Promise<boolean> {
		const requiredPermission = this.reflector.getAllAndOverride<string>(PERMISSION_KEY, [
			context.getHandler(),
			context.getClass(),
		]);
		if (!requiredPermission) {
			return true;
		}

		console.log(context.switchToHttp().getRequest().headers.authorization);
		const token = context.switchToHttp().getRequest().headers.authorization;
		const decoded = this.authService.getTokenData(token);
		console.log(decoded.roleId);
		const permissions = await this.authService.getUserAllPermissionList(decoded.roleId);
		// console.log(permissions.data);
		console.log('AuthPermissionGuard');
		// throw new HttpException(
		// 	{
		// 		code: HttpStatus.UNAUTHORIZED,
		// 		data: null,
		// 		msg: '登录已过期',
		// 	},
		// 	HttpStatus.UNAUTHORIZED,
		// );
		return !!token;
	}
}
